//
//  KaiMenViewController.m
//  ZHBLE
//
//  Created by Apple on 16/9/21.
//  Copyright © 2016年 zhuo. All rights reserved.
//

#import "KaiMenViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "AFNetworking.h"
@interface KaiMenViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate, UIAlertViewDelegate>
//蓝牙中心管理者
@property (strong, nonatomic) CBCentralManager *centralManger;

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong)UILabel *UUIDLabel;
//用于保存外设
@property (nonatomic, strong)CBPeripheral*peripheral;
//用于保存外设名字
@property (nonatomic, strong)NSString *peripheralAd;
//用于保存开门指令
@property (nonatomic, strong)NSData *door_order;

@property (nonatomic, strong)CBCharacteristic *notifyCharacteristic;

@property (nonatomic, strong)CBCharacteristic *writeCharacteristic;

@property (nonatomic, assign)NSInteger type;
@end

@implementation KaiMenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"靠浦开门";
    //开启摇一摇事件
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];
    
    //设置蓝牙中心
    self.centralManger = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    imageView.image = [UIImage imageNamed:@"bg.png"];
    [self.view addSubview:imageView];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(210, 290, 40, 40)];
    self.imageView.image = [UIImage imageNamed:@"摇晃1.png"];
    [self.view addSubview:self.imageView];
    
    self.UUIDLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 30, 350, 20)];
    self.UUIDLabel.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.UUIDLabel];
    self.UUIDLabel.font = [UIFont systemFontOfSize:14];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"前往设置打开蓝牙" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != 0) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}


//摇一摇开始事件
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion != UIEventSubtypeMotionShake) return;
    NSLog(@"开始摇一摇");
    self.type = 1;
    NSDictionary *options = @{CBCentralManagerScanOptionAllowDuplicatesKey: @(YES)};
    [self.centralManger scanForPeripheralsWithServices:nil options:options];
    //获取到当前View的layer
    CALayer *viewLayer = self.imageView.layer;
    //获取当前View的位置
    CGPoint position = viewLayer.position;
    //移动的两个终点位置
    CGPoint beginPosition = CGPointMake(position.x + 5, position.y);
    CGPoint endPosition = CGPointMake(position.x - 5, position.y);
    //设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    //设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    //设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:beginPosition]];
    //设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:endPosition]];
    //设置自动反转
    [animation setAutoreverses:YES];
    //设置时间
    [animation setDuration:0.05];
    //设置次数
    [animation setRepeatCount:5];
    //添加上动画
    [viewLayer addAnimation:animation forKey:nil];
}

//摇一摇结束事件
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion != UIEventSubtypeMotionShake) return;
    NSLog(@"摇一摇结束");
}

//中心设备状态更新
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            break;
    }

}

//发现外设获取信号最强外设
- (void)centralManager:(CBCentralManager *)central
 didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary *)advertisementData
                  RSSI:(NSNumber *)RSSI
{
    
    int rssiNum = abs([RSSI intValue]);
    CGFloat ci = (rssiNum - 59) / (10 * 2.);
    
    NSLog(@"ci：%f",ci);
    NSLog(@"pow：%.2f",pow(10,ci));
    NSLog(@"peripheral：%@",peripheral.name);
    NSLog(@"%@", advertisementData);
    if ([advertisementData[@"kCBAdvDataLocalName"] hasPrefix:@"KP"] && (ABS([RSSI integerValue]) > 35)  && ci <= 0.5){
        [self.centralManger stopScan];
        if (self.peripheral != peripheral) {
            self.peripheral = peripheral;
        }
        //连接设备
        [self.centralManger connectPeripheral:self.peripheral options:nil];
        self.peripheralAd = advertisementData[@"kCBAdvDataLocalName"];
        self.UUIDLabel.text = self.peripheralAd;

    }
}

//中心与外设连接
- (void)centralManager:(CBCentralManager *)central
  didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>连接到名称为（%@）的设备-成功",peripheral.identifier);
    NSLog(@"已连接设备信息：%@", peripheral);
    //设置的peripheral委托CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:self];
    //扫描外设Services，成功后会进入方法：-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];
    // 网络请求 并且传入外设ID   peripheral.name
    [self getHttp:self.peripheralAd];
}

- (void)getHttp:(NSString *)peripheralAd {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    configuration.HTTPAdditionalHeaders = @{};
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSLog(@"请求设备ID : %@",peripheralAd);
    NSString *uid = [Common plistRead:@"uid"];
    NSString *sqid = [Common plistRead:@"sqid"];
    NSDictionary *dic = @{@"uid":uid,@"sqid":sqid,@"door_uuid":peripheralAd};
    [manager GET:HTTP_OPEN_DOOR_TOOTH parameters:dic  progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([dic[@"recode"] isEqualToString:@"0"]) {
                NSLog(@"door_order : %@", dic[@"door_order"]);
                self.door_order = [self strTo16Data:dic[@"door_order"]];
            } else {
                NSLog(@"ErrorMsg : %@", dic[@"msg"]);
                [self.centralManger cancelPeripheralConnection:self.peripheral];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}


- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error
{
    
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
   
    if (error)
    {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics){
        {
            [peripheral readValueForCharacteristic:characteristic];
        }
    }
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic];
    }
}

//获取的charateristic的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //打印出characteristic的UUID和值
    //!注意，value的类型是NSData，具体开发时，会根据外设协议制定的方式去解析数据
    
    if (self.type == 1) {
        NSLog(@"characteristic uuid:%@  value:%@",[characteristic.UUID UUIDString],characteristic.value);
    } else if (self.type == 2) {
        if (characteristic == self.notifyCharacteristic && peripheral == self.peripheral) {
            
            NSString *string = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
            NSString *string1 = [NSString stringWithFormat:@"%@", characteristic.value];
            NSLog(@"!!!!!!!!!!!!!!%@", characteristic.value);
            NSLog(@"转换 : %@", string1);
            if (self.door_order == nil) {
                NSLog(@"开门失败");
            } else if (self.door_order != nil) {
                if ([string1 isEqualToString:@"<5aa5020b b0>"]) {
                    NSLog(@"开门成功");
                    [self.centralManger stopScan];
                    [self.centralManger cancelPeripheralConnection:self.peripheral];
                } else if ([string1 isEqualToString:@"<5aa5030b b0>"]){
                    NSLog(@"开门失败");
                    [self.centralManger stopScan];
                    [self.centralManger cancelPeripheralConnection:self.peripheral];
                }
                NSLog(@"*******************************");
                NSLog(@"****characteristic uuid:%@  value:%@",[characteristic.UUID UUIDString],characteristic.value);
            }
        }
    }
}

//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
//    NSLog(@"characteristic : %lu", characteristic.properties);
    
    if ([[characteristic.UUID UUIDString] hasSuffix:@"9616"]) {
        self.notifyCharacteristic = characteristic;
        [self notifyCharacteristic:self.peripheral characteristic:self.notifyCharacteristic];

    }
    
    if ([[characteristic.UUID UUIDString] hasSuffix:@"BB3"]) {
        if (characteristic) {
            if (![self.door_order isKindOfClass:[NSNull class]]) {
                NSLog(@"data : %@",self.door_order);
                self.writeCharacteristic = characteristic;
                [self writeCharacteristic:self.peripheral characteristic:self.writeCharacteristic value:self.door_order];

            } else {
                NSLog(@"description : %@", self.door_order.description);
            }
        } else {
            NSLog(@"重新连接");
            NSLog(@"%@", self.peripheral);
        }
    }
}
//获取到Descriptors的值
//-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
//    //打印出DescriptorsUUID 和value
//    //这个descriptor都是对于characteristic的描述，一般都是字符串，所以这里我们转换成字符串去解析
//    NSLog(@"FIRST characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
//}

//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value{
      //只有 characteristic.properties 有write的权限才可以写
    NSLog(@"value : %@", value);
    if(characteristic.properties & CBCharacteristicPropertyWrite && value != nil){
        /*
         最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
         */
        NSLog(@"传入：%@", peripheral);
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
//        self.peripheral = nil;
        NSLog(@"保存的外设：%@", self.peripheral);
        self.UUIDLabel.text = @"";
    }else{
        NSLog(@"开门失败");
        [self cancelNotifyCharacteristic:self.peripheral characteristic:self.notifyCharacteristic];
    }
}

//设置通知
-(void)notifyCharacteristic:(CBPeripheral *)peripheral
             characteristic:(CBCharacteristic *)characteristic{
    //设置通知，数据通知会进入：didUpdateValueForCharacteristic方法
    [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
}

//取消通知
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
                   characteristic:(CBCharacteristic *)characteristic{
    [self.peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

//通知回执
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
    NSLog(@"通知 : %@",characteristic.description);
    self.type = 2;

}

//字符串转16进制
- (NSData *)strTo16Data:(NSString *)str {
    NSMutableArray *strArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < str.length; i += 2) {
        NSRange range = NSMakeRange(i, 2);
        [strArr addObject:[str substringWithRange:range]];
    }
    char charArr[strArr.count];
    for (int i = 0; i < strArr.count; i++) {
        unsigned long red = strtoul([[strArr objectAtIndex:i] UTF8String],0,16);
        charArr[i] = red;
    }
    NSData *data = [NSData dataWithBytes:charArr length:strArr.count];
    return data;
}

@end
